<template>
  <div class="chart_container" v-if="currentList && currentList.length">
    <template v-for="code in currentList" :key="code">
      <template v-for="item in channel" :key="item">
        <div :class="['box', item, code.replaceAll('.', '')]"></div>
      </template>
    </template>
  </div>
  <div class="chart_container empty" v-else>
    <Empty :image="simpleImage"></Empty>
  </div>
</template>

<script setup lang="tsx">
import { computed, inject, nextTick, ref, watch } from 'vue';
import { Empty, message } from 'ant-design-vue';
import * as echarts from 'echarts';
import 'echarts/theme/macarons';

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
const props = defineProps({
  channel: {
    type: Array,
    default: [],
  },
  presentation: {
    type: Array,
    default: [],
  },
  deviceInfo: {
    type: Array,
    default: [],
  },
  data: {
    type: Object,
    default: () => {},
  },
  formatWave: {
    type: null,
  },
});
const devices = ref([]);
const colorEnum = {
  EIZ: '#FF5C8D',
  EIN: '#FFE54E',
  EIE: '#39D0FF',
};
watch(
  () => props,
  (val) => {
    // 通道
    nextTick(() => {
      if (!Object.keys(val.data).length) return;
      dataInfo.value = val.data;
      getInfo(val.channel, val.presentation[0], val.deviceInfo);
    });
  },
  { deep: true, immediate: true },
);
const { formatWave } = props;
const dataInfo = ref(props.data);
const currentList = computed(() => {
  const asyncKeys = Object.keys(dataInfo.value);

  return devices.value.filter((i) => asyncKeys.includes(i.replaceAll('.', '')));
});

const processFn = (code, node, data, type, channel) => {
  if (formatWave && typeof formatWave === 'function')
    return formatWave(code, node, data, type, channel);
  const i = data[0].i;
  const seriesData = data.map((i) => {
    if (i.xf == 0) return;
    return [i.xf, Number(i.g?.toFixed(6))];
  });
  const allData = data.map((i) => i.g.toFixed(6));
  const max = Math.max.call(null, ...allData);
  const min = Math.min.call(null, ...allData);
  const text =
    [code, i, channel].join('.') +
    ' - 加速度傅立叶谱[幅值' +
    (type == 'log' ? 'log' : '') +
    '(cm/s/s)---频率(Hz)]' +
    '   Amax=' +
    (type == 'value' ? max : Math.log10(max).toFixed(6)) +
    '  Amin=' +
    (type == 'value' ? min : Math.log10(min).toFixed(6));
  const color = colorEnum[channel];

  return { text, node, seriesData, type, color };
};
const getInfo = (list, type, deviceList) => {
  devices.value = deviceList;
  for (const code in dataInfo.value) {
    const keys = deviceList.map((i) => i.replaceAll('.', ''));
    if (!keys.includes(code)) return;
    list.forEach((channel) => {
      nextTick(() => {
        const nodes = document.querySelectorAll(
          `.${channel}.${code.replaceAll('.', '')}`,
        );
        nodes.forEach((node) => {
          const result = processFn(
            code,
            node,
            dataInfo.value[code][conversion(channel)],
            type,
            channel,
          );
          init(result);
        });
      });
    });
  }
};
const init = ({ text, node, seriesData, type, color }) => {
  chart && chart.dispose();
  var chart = echarts.init(node);
  const option = {
    title: {
      text,
      textStyle: {
        color: '#fff',
        fontSize: 14,
      },
      top: '4%',
      left: '4%',
    },
    grid: [
      {
        top: '25%',
        bottom: '15%',
        right: '3%',
        left: '4%',
        show: true,
      },
    ],
    xAxis: [
      {
        show: true,
        type: type == 'value' ? 'category' : type,
        splitLine: {
          show: false,
          lineStyle: {
            type: 'dashed',
          },
        },
        // splitNumber: 8,
        axisLine: {
          show: false,
          onZero: false,
        },
        // inverse: true,
        axisTick: {
          show: false,
        },
        // interval:2,
        // data: this.Xdata[key],
        axisLabel: {
          color: '#fff',
          show: true,
          showMaxLabel: true,
          // formatter: function (params) {
          //     return type == 'value' ? params : Math.log10(params)
          // },
        },
        max: function (value) {
          //取最大值向上取整为最大刻度
          return value.max;
        },
      },
    ],
    yAxis: [
      {
        type: type,
        splitLine: {
          show: false,
          lineStyle: {
            type: 'dashed',
          },
        },
        axisLine: {
          show: false,
          onZero: false,
        },
        axisLabel: {
          color: '#fff',
          fontSize: '12px',
          formatter: function (params) {
            return type == 'value' ? params : Math.log10(params);
          },
        },
        axisTick: {
          show: false,
        },
        // max: function (value) {//取最大值向上取整为最大刻度
        //     return value.max
        // },
        // min: function (value) {//取最大值向上取整为最大刻度
        //     return value.min
        // },
        scale: true,
      },
    ],
    series: [
      {
        data: seriesData,
        type: 'line',
        showSymbol: false,
        markPoint: {
          symbol: 'pin',
          symbolSize: 30,
          itemStyle: {
            color: 'blue',
          },
          data: [
            {
              name: '最大值',
              type: 'max',
              label: {
                formatter: function (params) {
                  return type == 'value'
                    ? params.data.value
                    : Math.log10(params.data.value).toFixed(6);
                },
              },
            },
            {
              name: '最大值',
              type: 'min',
              label: {
                formatter: function (params) {
                  return type == 'value'
                    ? params.data.value
                    : Math.log10(params.data.value).toFixed(6);
                },
              },
            },
          ],
        },
        // animationDurationUpdate: 1000,
        lineStyle: {
          //设置线条默认样式
          normal: {
            width: 1,
            color,
          },
          //设置线条hover样式
          emphasis: { width: 1 },
        },
      },
    ],
    animationDurationUpdate: 500,
  };
  chart.setOption(option);
  addEventListener('resize', function () {
    chart.resize();
  });
};

const conversion = (num) => {
  switch (num) {
    case 'EIZ':
      return 'a';
    case 'EIN':
      return 'b';
    case 'EIE':
      return 'c';
  }
};
</script>

<style lang="scss" scoped>
.chart_container {
  width: 100%;
  // height: 100%;
  display: grid;
  grid-template-rows: repeat(3, 1fr);
  gap: 1vh;
  .box {
    height: 25vh;
  }
  &.empty {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
